#coding=utf-8
#LightCam 自定义监控程序
#init by hfh 20150212

import socket,os,time,re,subprocess,traceback,sys


if __name__ == "__main__":

	cmd='echo $LIGHTCAM_HOME'
	popen=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	while True:
		if popen.poll()==None:
			time.sleep(0.1)
			continue
		else:
			break
	lchome=popen.stdout.read().strip('\r\n')
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	logfile=file(logfilename,'a')
	
	#执行命令
	while True:
		try:
			for line in open(confname):
				name=line.split("\t")[0]
				comd=line.split("\t")[1]
				popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
				#判断子进程是否结束
				while True:
					if popen.poll()==None:
						time.sleep(0.1)
						continue
					else:
						break
				#处理程序
				line=popen.stdout.read().strip("\n").strip("\r")
				today=time.strftime('%Y%m%d',time.localtime())
				now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				strs="echo \""+str(now)+" "+str(line)+" \">>../data/"+str(name)+"/"+str(today)
	#			print strs
				os.system(strs)
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				logfile.write(logdate+" "+str(name)+"\n")
				logfile.flush()
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" 阈值配置文件读取失败:\n"+excinfo+"\n")
			logfile.flush()
		time.sleep(600)
